package com.zyz.system.service.user.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyz.common.core.enums.ResultCodeEnum;
import com.zyz.common.core.model.TableDataInfo;
import com.zyz.common.security.exception.ServiceException;
import com.zyz.system.manager.UserCacheManager;
import com.zyz.system.mapper.user.UserMapper;
import com.zyz.system.model.user.User;
import com.zyz.system.model.user.dto.UserQueryDTO;
import com.zyz.system.model.user.dto.UserStatusDTO;
import com.zyz.system.model.user.vo.UserVO;
import com.zyz.system.service.user.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserCacheManager userCacheManager;


    @Override
    public TableDataInfo list(UserQueryDTO userQueryDTO) {
        PageHelper.startPage(userQueryDTO.getPageNumber(), userQueryDTO.getPageSize());
        List<UserVO> userVOs = userMapper.selectUserList(userQueryDTO);
        if (userVOs == null || userVOs.isEmpty()) {
            return TableDataInfo.empty();
        }
        long total = new PageInfo<>(userVOs).getTotal();
        return TableDataInfo.success(userVOs,total);
    }

    @Override
    public void updateStatus(UserStatusDTO userStatusDTO) {
        // 判断用户是否存在
        User user = userMapper.selectById(userStatusDTO.getUserId());
        if (user == null) {
            log.error("用户不存在,用户id: {}" , userStatusDTO.getUserId());
            throw new ServiceException(ResultCodeEnum.FAILED_USER_NOT_EXISTS);
        }
        user.setStatus(userStatusDTO.getStatus());
        int row = userMapper.updateById(user);
        if (row != 1) {
            log.error("更改用户状态失败");
            throw new ServiceException(ResultCodeEnum.ERROR);
        }
        // 更新缓存
        userCacheManager.refreshUserStatus(userStatusDTO.getUserId(), userStatusDTO.getStatus());

    }
}
